angular.module('RDash')
    .controller('AuthCtrl', ['app', 'restService', 'commonService', '$scope', '$http', '$window', "templateService", AuthCtrl]);

function AuthCtrl(app, restService, commonService, $scope, $http, $window, templateService) {
    console.log('auth-ctrl');
    app.setCurUrl('/auth');

    $scope.author = app.getAuthor();
    $scope.birthday = null;
    $scope.sexs = [
        {id: 0, name: "无"},
        {id: 1, name: "男"},
        {id: 2, name: "女"}];
    if ($scope.author != null && $scope.author.birthday != null) {
        $scope.birthday = new Date($scope.author.birthday);
    }

    $scope.alterInfo = function () {
        try {
            parseInt($scope.author.age);
        } catch (e) {
            $scope.age = 0;
        }

        var birthday = null;
        if ($scope.birthday != null) {
            // birthday = $filter('date')($scope.birthday.valueOf(), 'yyyy-MM-dd hh:mm:ss');
            // console.log(birthday);
            birthday = $scope.birthday.valueOf();
        }

        $http({
            method: 'POST',
            url: restService.create("user/alterUserInfo"),
            data: {
                'username': $scope.author.username,
                'nickname': $scope.author.nickname,
                'sex': $scope.author.sex,
                'age': $scope.author.age,
                'birthday': birthday
            }
        }).then(function successCallback(response) {
            if (app.catchResultCode(response.data['resultCode'])) {
                restService.api.user.save({
                    ID: 'watchUserInfo'
                }, null, function (result) {
                    if (result['resultCode'] == 0) {
                        app.setAuthor(angular.fromJson(result["data"]));

                        commonService.toast.putOToast({
                            method: 'success',
                            info: '个人信息修改成功！'
                        });
                        $window.location.reload();
                    }
                });
            }
        }, function errorCallback(response) {
            console.log(response);
        });
    };

    $scope.resetPassword = function () {
        templateService.resetPassword($scope.author.username);
    };
}